"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 执行gs_uninstall命令卸载数据库，某主机做单点卸载后，openGauss不能再做全量卸载。
Create At   : 2022/1/6
@zou_jialiang0501129488
Description :
    1.下载解压数据库安装包
    2.配置xml文件并创建初始用户并修改文件属组
    3.gs_preinstall预安装：
    4.gs_install安装1主1备：
    5.执行gs_uninstall --delete-data -L
    6.执行gs_uninstall --delete-data
    7.清理环境
Expect      :
    1.下载解压成功
    2.配置成功，创建成功
    3.预安装成功
    4.安装成功
    5.单点卸载成功
    6.全量卸载失败报错
    7.清理成功
History     :
    modified by @daiguatutu at 2022-11-7:优化用例,增加预安装超时时间
    modified by @daiguatutu at 2022-11-15:优化用例,增加预安装超时时间
    modified by @daiguatutu at 2022-11-23:修改参数shared_buffers值,增加超时时间,避免性能问题安装失败
"""
import os
import re
import unittest

from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

primary_sh = CommonSH('PrimaryDbUser')
Constant = Constant()


@unittest.skipIf(1 >= primary_sh.get_node_num(), '单机环境不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_root_node = Node('PrimaryRoot')
        self.standby1_root_node = Node('Standby1Root')
        self.primary_node = Node('PrimaryDbUser')
        self.standby_node = Node('Standby1DbUser')
        self.common = Common()
        self.u_name = 'gs_uninstall_0006'
        instance_path = macro.DB_INSTANCE_PATH
        for num in range(macro.DB_INSTANCE_PATH.count('/') - 1):
            instance_path = os.path.dirname(instance_path)
        self.dir_path = os.path.join(instance_path, self.u_name)
        self.package_path = os.path.join(self.dir_path, 'pkg')
        self.conf_path = os.path.join(self.dir_path, 'config')
        self.data_path = os.path.join(self.dir_path, 'cluster')
        self.xml_path = os.path.join(self.conf_path, 'primary_standby.xml')
        self.env_path = os.path.join(self.conf_path, 'env')
        self.script_path = os.path.join(self.package_path, 'script')

    def test_gs_uninstall(self):
        text = '-----step1:下载解压数据库安装包 expect:下载解压成功-----'
        self.log.info(text)
        self.common.check_load_msg(self.primary_root_node, self.primary_node,
                                   self.package_path, self.conf_path)

        test = '-----查看主机名-----'
        self.log.info(test)
        pri_node_name = self.common.get_sh_result(self.primary_root_node,
                                                  "uname -n")
        self.assertIsNotNone(pri_node_name, '执行失败:' + text)
        sta_node_name = self.common.get_sh_result(self.standby1_root_node,
                                                  "uname -n")
        self.assertIsNotNone(sta_node_name, '执行失败:' + text)

        test = '-----查询系统未使用端口-----'
        self.log.info(test)
        port = self.common.get_not_used_port(self.primary_node)
        self.assertNotEqual(0, port, '执行失败:' + text)

        text = '-----step2:配置xml文件并创建初始用户并修改文件属组 expect:成功-----'
        self.log.info(text)
        gaussdb_app_path = os.path.join(self.data_path, 'app')
        gaussdb_log_path = os.path.join(self.data_path, 'gaussdb_log')
        tmpmppdb_path = os.path.join(self.data_path, 'tmp')
        gaussdb_tool_path = os.path.join(self.data_path, 'tool')
        data_node1 = os.path.join(self.data_path, 'dn1')
        self.common.scp_file(self.primary_root_node, 'primary_standby.xml',
                             self.conf_path)
        xml_cmd = f"sed -i 's#v_nodeNames#{pri_node_name},{sta_node_name}" \
            f"#g' {self.xml_path};" \
            f"sed -i 's#v_gaussdbAppPath#{gaussdb_app_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_gaussdbLogPath#{gaussdb_log_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_tmpMppdbPath#{tmpmppdb_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_gaussdbToolPath#{gaussdb_tool_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_corePath#{macro.DB_CORE_PATH}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_db_host#{self.primary_node.db_host}," \
            f"{self.standby_node.db_host}#g' {self.xml_path};" \
            f"sed -i 's#v_pri_nodeNames#{pri_node_name}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_pri_db_host#{self.primary_node.db_host}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_dataPortBase#{port}#g' {self.xml_path};" \
            f"sed -i 's#v_dataNode1#{data_node1},{sta_node_name}," \
            f"{data_node1}#g' {self.xml_path};" \
            f"sed -i 's#v_sta_nodeNames#{sta_node_name}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_sta_db_host#{self.standby_node.db_host}#g' " \
            f"{self.xml_path};" \
            f"cat {self.xml_path}"
        self.log.info(xml_cmd)
        result = self.common.get_sh_result(self.primary_root_node, xml_cmd)
        msg_list = [pri_node_name, self.primary_node.db_host,
                    sta_node_name, self.standby_node.db_host,
                    self.data_path, f"{port}"]
        for content in msg_list:
            self.assertIn(content, result, '执行失败:' + text)
        self.assertIn('gaussdbLogPath', result, '执行失败:' + text)

        self.log.info('-----创建初始用户并修改密码-----')
        self.common.create_user(self.primary_root_node, self.u_name)
        self.common.create_user(self.standby1_root_node, self.u_name)
        file_own = f'chown -R {self.u_name}:{self.u_name} {self.dir_path}'
        self.log.info(file_own)
        file_msg = self.common.get_sh_result(self.primary_root_node, file_own)
        self.assertEqual('', file_msg, '执行失败:' + test)

        text = '-----step3:执行gs_preinstall命令 expect:预安装成功-----'
        self.log.info(text)
        preinstall_cmd = f'./gs_preinstall -U {self.u_name} ' \
                         f'-G {self.u_name} -X {self.xml_path}' \
                         f' --sep-env-file={self.env_path} --skip-hostname-set '
        execute_cmd = f'''cd {self.script_path}
                       expect <<EOF
                       set timeout 2000
                       spawn {preinstall_cmd}
                       expect "*(yes/no)?"
                       send "yes\\n"
                       expect "Password:"
                       send "{self.primary_root_node.ssh_password}\\n"
                       expect "*(yes/no)?"
                       send "yes\\n"
                       expect "Password:"
                       send "{macro.COMMON_PASSWD}\\n"
                       expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        msg = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        self.assertIn(Constant.preinstall_success_msg, msg,
                      '执行失败:' + text)

        text = '-----step4:执行gs_install命令 expect:安装成功-----'
        self.log.info(text)
        su_cmd = f'su - {self.u_name}'
        install_cmd = f'gs_install -X {self.xml_path} ' \
            f'--dn-guc=shared_buffers=128MB'
        execute_cmd = f'''expect <<EOF
                       set timeout 600
                       spawn {su_cmd}
                       expect "$"
                       send "source {self.env_path}\\n"
                       expect "$"
                       send "{install_cmd}\\n"
                       expect "Please enter password for database:"
                       send "{macro.COMMON_PASSWD}\\n"
                       expect "Please repeat for database:"
                       send "{macro.COMMON_PASSWD}\\n"
                       expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        exec_msg = self.common.get_sh_result(self.primary_root_node,
                                             execute_cmd)
        self.assertIn(Constant.install_success_msg, exec_msg, '执行失败:' + text)

        text = '-----step5:执行gs_uninstall --delete-data -L命令 ' \
               'expect:单点卸载成功-----'
        self.log.info(text)
        execute_cmd = f'su - {self.u_name} <<EOF\n' \
                      f'source {self.env_path};' \
                      f'gs_uninstall --delete-data -L;\n' \
                      f'EOF'
        self.log.info(execute_cmd)
        msg = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        self.assertIn(Constant.uninstall_success_msg, msg, '执行失败:' + text)

        text = '-----step6:执行gs_uninstall --delete-data命令 ' \
               'expect:全量卸载失败-----'
        self.log.info(text)
        execute_cmd = f'su - {self.u_name} <<EOF\n' \
                      f'source {self.env_path};' \
                      f'gs_uninstall --delete-data;\n' \
                      f'EOF'
        self.log.info(execute_cmd)
        msg = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        self.log.info(msg)
        self.assertNotIn(Constant.uninstall_success_msg, msg, '执行失败:' + text)
        text_1 = '-----备机执行gs_uninstall -L单点卸载 expect:成功-----'
        self.log.info(text_1)
        execute_cmd = f'su - {self.u_name} <<EOF\n' \
                      f'source {self.env_path};' \
                      f'gs_uninstall --delete-data -L;\n' \
                      f'EOF'
        self.log.info(execute_cmd)
        uninstall_msg = self.standby1_root_node.sh(execute_cmd).result()
        self.assertIn(Constant.uninstall_success_msg, uninstall_msg, '卸载失败')

    def tearDown(self):
        self.log.info('-----step7:清理环境-----')
        text_2 = '-----删除用户下进程 expect:成功-----'
        self.log.info(text_2)
        kill_flag = False
        dir_flag = False
        user_flag = False
        kill_cmd = f"ps -u {self.u_name} | grep -v PID | " \
                   f"awk \'{{{{print $1}}}}\' | xargs kill -9;" \
                   f"ipcs -m|awk '{{{{if($3~/^[0-9]+$/) {{{{print $2}}}}}}}}'" \
                   f" | xargs -I {{{{}}}} ipcrm -m {{{{}}}};" \
                   f"ipcs -s|awk '{{{{if($3~/^[0-9]+$/) {{{{print $2}}}}}}}}'" \
                   f" | xargs -I {{{{}}}} ipcrm -s {{{{}}}};sync;" \
                   f"echo 3 > /proc/sys/vm/drop_caches"
        self.log.info(kill_cmd)
        for count in range(10):
            pri = self.common.get_sh_result(self.primary_root_node, kill_cmd)
            sta1 = self.common.get_sh_result(self.standby1_root_node, kill_cmd)
            if pri and sta1:
                self.log.info('process killed')
                kill_flag = True
                break
        text_3 = '-----删除用户及数据准备目录 expect:成功-----'
        self.log.info(text_3)
        check_cmd = f'rm -rf {self.dir_path};' \
                    f'if [ -d {self.dir_path} ]; ' \
                    f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(check_cmd)
        for count in range(10):
            pri = self.common.get_sh_result(self.primary_root_node, check_cmd)
            sta1 = self.common.get_sh_result(self.standby1_root_node, check_cmd)
            if 'not exists' in pri and 'not exists' in sta1:
                self.log.info('file deleted')
                dir_flag = True
                break
        usr_cmd = f'userdel -rf {self.u_name};id {self.u_name}'
        for count in range(10):
            pri = self.common.get_sh_result(self.primary_root_node, usr_cmd)
            sta1 = self.common.get_sh_result(self.standby1_root_node, usr_cmd)
            if 'no such user' in pri and 'no such user' in sta1:
                self.log.info('user deleted')
                user_flag = True
                break
        self.assertTrue(kill_flag, '清理环境失败')
        self.assertTrue(dir_flag, '清理环境失败')
        self.assertTrue(user_flag, '清理环境失败')
        self.log.info(f'-----{os.path.basename(__file__)} finish-----')

